package org.product.chat.socket;


import com.google.gson.Gson;
import org.product.chat.entity.Message;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * WebSocket服务器端程序：实现聊天服务
 * @author zqx
 * @date 2020-12-22
 */
@ServerEndpoint("/chatSocket")
public class ChatSocket {
    private String username ;

    // 存放所有的用户，以及对应的Session对象
    private static Map<String,Session> sessionMap = new HashMap<String,Session>() ;

    // 用于存储当前聊天室存在的所有的用户
    private static List<String> usernameList = new ArrayList<String>() ;

    public ChatSocket() {
        System.out.println("chatSocket....");
    }

    @OnOpen
    public void open(Session session) {
        String queryString = session.getQueryString();
        String username = queryString.substring(queryString.indexOf("=") + 1);

        this.username = username;
        sessionMap.put(this.username, session);
        usernameList.add(this.username);
        String info = "欢迎 " + this.username + " 进入聊天室!";

        Message message = new Message();
        message.setInfo(info);
        message.setUserList(usernameList);

        Gson gson = new Gson();
        String json = gson.toJson(message);

        broadcast(sessionMap, json);

    }

    @OnClose
    public void close(Session session) {
        // 退出登录时提示信息
        String info = this.username + "退出聊天室!";

        // 移除session和登录用户
        sessionMap.remove(this.username) ;
        usernameList.remove(this.username);

        // 封装信息
        Message message = new Message();
        message.setInfo(info);
        message.setUserList(usernameList);

        Gson gson = new Gson();
        String json = gson.toJson(message);

        // 广播信息
        broadcast(sessionMap, json);

    }

    @OnMessage
    public void sendMessage(Session session,String msg,boolean last) {
        Gson gson = new Gson();
        Message message = gson.fromJson(msg, Message.class);

        if (message.getType() == 1) {
            // 群聊
            message.setMessage(this.username, message.getMessage());
            message.setUserList(usernameList);
            String json = gson.toJson(message);
            broadcast(sessionMap, json);
        } else {
            // 私聊
            Session toSession = sessionMap.get(message.getTo());

            message.setMessage(this.username, message.getMessage());
            message.setUserList(usernameList);

            String json = gson.toJson(message);

            Map<String,Session> maps = new HashMap<String,Session>() ;
            maps.put(message.getTo(), toSession) ;
            maps.put(this.username,session);
            broadcast(maps, json);
        }

        System.out.println("->" + message);
    }


    /**
     * 广播信息
     * @param sessionMap
     * @param msg
     */
    private void broadcast(Map<String,Session> sessionMap, String msg) {
        for (Map.Entry<String, Session> entry : sessionMap.entrySet()) {
            Session session = entry.getValue() ;
            try {
                session.getBasicRemote().sendText(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
